# -*- coding: utf-8 -*-

import os
import sys
import json
from log.logger import logger

reload(sys)
sys.setdefaultencoding('utf-8')

def json_loads(jstr):
    try:
        obj = json.loads(jstr)
        #logger.info("Load [{0}] to python object [{1}] successfully.".format(jstr, obj))
    except Exception, e:
        obj = None
        logger.error("Load [{0}] to python object failed: [{1}]".format(jstr, e))

    return obj


def json_dumps(obj, indent=None, ensure_ascii=True):
    try:
        jstr = json.dumps(obj, separators=(',', ': '), sort_keys=True, indent=indent, ensure_ascii=ensure_ascii)
        #logger.info("Dump [{0}] to json string [{1}] successfully.".format(obj, jstr))
    except Exception, e:
        jstr = None
        logger.error("Dump [{0}] to json string failed: [{1}]".format(obj, e))

    return jstr


def json_load(jfile):
    if os.path.exists(jfile):
        try:
            with open(jfile, 'r') as json_file:
                obj = json.load(json_file)
            #logger.info("Load [{0}] to python object [{1}] successfully!".format(jfile, obj))
        except Exception, e:
            obj = None
            logger.error("Load [{0}] to python object failed: [{1}]".format(jfile, e))
    else:
        obj = None
        logger.error("Load [{0}] to python object failed! Json file [{0}] do not exist!".format(jfile))

    return obj


def json_dump(obj, jfile, sort_keys=True, indent=4):
    try:
        with open(jfile, 'w') as json_file:
            json.dump(obj, json_file, sort_keys=sort_keys, indent=indent, separators=(',', ': '))
        #logger.info("Dump [{0}] to json file [{1}] successfully!".format(obj, jfile))
    except Exception as e:
        logger.error("Dump [{0}] to json file [{1}] failed: [{2}]".format(obj, jfile, e))
